//
//  WHInFailureController.m
//  SquirrelSeller
//
//  Created by 邓伟浩 on 2019/1/6.
//  Copyright © 2019 邓伟浩. All rights reserved.
//

#import "WHInFailureController.h"
#import "WHInFailureCell.h"
#import "WHNoDataViewTool.h"

@interface WHInFailureController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *dataTableView;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;
@property (nonatomic, strong) UIButton *allInBtn;

@end

@implementation WHInFailureController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"入库失败列表";
    
    [self initParams];
    [self setUpTableView];
    [self setUpAllInBtn];
    
    [self showNoDataView];
}

- (void)initParams {
    _page = 1;
    _dataArray = @[].mutableCopy;
}

- (void)setUpAllInBtn {
    UIButton *allInBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:allInBtn];
    [allInBtn setBackgroundImage:[UIImage imageWithColor:CMDarkOrangeColor] forState:UIControlStateNormal];
    [allInBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).offset(kRealwidth(32));
        make.right.mas_equalTo(self.view.mas_right).offset(-kRealwidth(32));
        make.height.mas_equalTo(kRealwidth(45));
        if (@available(iOS 11.0, *)) {
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-kRealwidth(20));
        } else {
            make.bottom.mas_equalTo(self.view.mas_bottom).offset(-kRealwidth(20));
        }
    }];
    NSString *str = @"全部重新入库";
    NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName:SYSTEMFONT(kRealwidth(17)), NSForegroundColorAttributeName:KWhiteColor}];
    [allInBtn setAttributedTitle:attributeStr forState:UIControlStateNormal];
    [allInBtn addTarget:self action:@selector(allInAgain:) forControlEvents:UIControlEventTouchUpInside];
    ViewRadius(allInBtn, kRealwidth(45)/2);
    _allInBtn = allInBtn;
}

- (void)setUpTableView {
    UITableView *dataTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    dataTableView.delegate = self;
    dataTableView.dataSource = self;
    [self.view addSubview:dataTableView];
    
    [dataTableView registerClass:[WHInFailureCell class] forCellReuseIdentifier:NSStringFromClass([WHInFailureCell class])];
    
    dataTableView.tableFooterView = [UIView new];
    dataTableView.backgroundColor = KClearColor;
    dataTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [dataTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.equalTo(@kTopHeight);
    }];
//
//    kWeakSelf(self);
//    dataTableView.mj_header = [WHGifHeader headerWithRefreshingBlock:^{
//        [weakself headerRereshing];
//    }];
//
//    dataTableView.mj_footer = [WHGifFooter footerWithRefreshingBlock:^{
//        [weakself footerRereshing];
//    }];
//    dataTableView.mj_footer.hidden = YES;
    _dataTableView = dataTableView;
}

- (void)showNoDataView {
    self.dataTableView.tableFooterView = [self noMoreDataFooterView];
    self.allInBtn.hidden = YES;
}

- (void)hideNoDataView {
    self.dataTableView.tableFooterView = [UIView new];
    self.allInBtn.hidden = NO;
}

- (UIView *)noMoreDataFooterView {
    UIView *tableFootView = [[UIView alloc] init];
    tableFootView.frame = CGRectMake(0, 0, KScreenWidth, kScreenHeight - kTopHeight - kRealwidth(35));
    
    [WHNoDataViewTool addNodataViewAt:tableFootView imageName:@"png_nodataView" tipsLabelText:@"暂无数据" tapAction:nil];
    
    return tableFootView;
}

- (void)headerRereshing {
    [self getInFailureListByPageNumber:1 completion:^(BOOL isSucess, BOOL isLast) {
        [self.dataTableView.mj_header endRefreshing];
        if (isSucess) {
            _page = 1;
            self.dataTableView.mj_footer.hidden = NO;
            if (isLast) {
                self.dataTableView.mj_footer.hidden = YES;
            } else {
                [self.dataTableView.mj_footer resetNoMoreData];
            }
        }
    }];
}

- (void)footerRereshing {
    [self getInFailureListByPageNumber:(_page+1) completion:^(BOOL isSucess, BOOL isLast) {
        if (isSucess) {
            if (isLast) {
                [self.dataTableView.mj_footer endRefreshingWithNoMoreData];
            } else {
                _page = _page + 1;
                [self.dataTableView.mj_footer endRefreshing];
            }
            
        } else {
            [self.dataTableView.mj_footer endRefreshing];
        }
        
    }];
    
}

#pragma mark - —————— UITableViewDelegate & UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WHInFailureCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHInFailureCell class]) forIndexPath:indexPath];
    cell.inFilureModel = [WHInFailureModel new];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRealwidth(140);
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kRealwidth(12);
}

#pragma mark - —————— 事件 ——————

/** 全部重新入库 */
- (void)allInAgain:(UIButton *)button {
    
}

#pragma mark - —————— 接口 ——————
- (void)getInFailureListByPageNumber:(int)pageNumber completion:(void (^)(BOOL isSucess, BOOL isLast))completion {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, @"");
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          @(pageNumber), @"pageNum",
                          nil];
    
    [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *errCode = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (errCode.intValue == 0) {
                NSDictionary *object = responseObject[@"retobj"];
                
                if (pageNumber == 1) {
                    [_dataArray removeAllObjects];
                }
                
                NSArray *stations = object[@"data"];
                if (stations.count == 0) {
                    if (completion) {
                        [self.dataTableView reloadData];
                        completion(YES, YES);
                    }
                    if (pageNumber == 1) {
                        DLog(@"没有数据");
                        [self showNoDataView];
                    }
                    return;
                }
                [self hideNoDataView];
                
                NSArray *tempStationArray = [NSArray modelArrayWithClass:[WHInFailureModel class] json:stations];
                [self.dataArray addObjectsFromArray:tempStationArray];
                [self.dataTableView reloadData];
                
                if (completion) {
                    completion(YES, NO);
                }
                
            } else {
                [WHView showMessage:errorMsg inView:self.view];
                if (completion) {
                    completion(NO, NO);
                }
            }
        }
    } failure:^(NSError *error) {
        if (completion) {
            completion(NO, NO);
        }
    }];
}

@end
